//
//  DiscussViewController.m
//  Car
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 岳明. All rights reserved.
//

#import "DiscussViewController.h"
#import "HTTPTOOL.h"
#import "MJRefresh.h"
#import "DiscussViewController.h"
#import "YZLDiscuss.h"

#import "YZLSelectTableHeader.h"
#import "YZLSelectTableViewCell0.h"
#import "TieDeatailViewController.h"
#import "AFN.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface DiscussViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)NSMutableArray *arr;

@property(nonatomic,assign)NSInteger nextPage;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉

@property (nonatomic, strong) YZLSelectTableHeader *header;
@property (nonatomic, strong) UITableView *table;

@property (nonatomic, strong) NSMutableArray *collectionArr;


@end

@implementation DiscussViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)creatTable {
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.table registerClass:[YZLSelectTableViewCell0 class] forCellReuseIdentifier:@"reuse0"];
    self.table.tableFooterView = [[UIView alloc]init];
    
    self.header = [[YZLSelectTableHeader alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200*HEIGHT/667) ];
    
    self.table.tableHeaderView = self.header;
    
    
    [self addHeader];
    [self addFooter];
    //自身的数组初始化
    self.arr = [NSMutableArray array];
    self.collectionArr = [NSMutableArray array];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YZLDiscuss *discuss = [self.arr objectAtIndex:indexPath.row];
    TieDeatailViewController *tie = [[TieDeatailViewController alloc] init];
    tie.discuss = discuss;
    DiscussViewController *disViewController = [DiscussViewController shareDiscussViewController];
    [disViewController.navigationController pushViewController:tie animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arr.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YZLSelectTableViewCell0 *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse0"];
    YZLDiscuss *discuss = [self.arr objectAtIndex:indexPath.row];
    cell.discuss = discuss;
    cell.selectionStyle = 0;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return WIDTH* 0.26667;
}




#pragma mark --下拉刷新
- (void)addHeader
{
    __weak DiscussViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    // 添加下拉刷新头部控件
    [self.table addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 0;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作.
        [vc GetPersonList:vc.nextPage];//重新请求数据
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.table headerBeginRefreshing];
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    __weak DiscussViewController *vc = self;
    // 添加上拉刷新尾部控件
    [self.table addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage +=20;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
    }];
}



-(void)GetPersonList:(NSInteger)nextCursor
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = [NSString stringWithFormat:@"http://mi.xcar.com.cn/interface/xcarapp/getSelectedPostList.php?limit=20&offset=%ld&ver=6.1.7",(long)nextCursor];
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"application/x-javascript",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [AFN urlString:url_string getAFNdata:^(id responseObject) {
        [netWorkManager stopMonitoring];
        YZLDiscuss *discuss = [YZLDiscuss DiscussWithDictionary:responseObject];
        NSArray *PostArr = discuss.focusPost;
        //海报图片数组
        
        
        if (PostArr.count > 0) {
            [self.collectionArr removeAllObjects];
            for (NSDictionary *dic in PostArr) {
                YZLDiscuss *d = [YZLDiscuss DiscussWithDictionary:dic];
                [self.collectionArr addObject:d];
            }
            YZLDiscuss *d0 = [self.collectionArr firstObject];
            YZLDiscuss *d1 = [self.collectionArr lastObject];
            [self.collectionArr insertObject:d1 atIndex:0];
            [self.collectionArr addObject:d0];
            self.header.arr = self.collectionArr;
        }
        
        NSArray *listArr = discuss.postList;
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.arr removeAllObjects];
        }
        
        for (NSDictionary *dic  in listArr) {
            YZLDiscuss *model = [YZLDiscuss DiscussWithDictionary:dic];
            [self.arr addObject:model];
        }
        
        [self.table footerEndRefreshing];
        [self.table headerEndRefreshing];
        [self.table reloadData];

    }];
    
    
    
    
    
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        YZLDiscuss *discuss = [YZLDiscuss DiscussWithDictionary:responseObject];
        NSArray *PostArr = discuss.focusPost;
        //海报图片数组
        

        if (PostArr.count > 0) {
            [self.collectionArr removeAllObjects];
            for (NSDictionary *dic in PostArr) {
                YZLDiscuss *d = [YZLDiscuss DiscussWithDictionary:dic];
                [self.collectionArr addObject:d];
            }
            YZLDiscuss *d0 = [self.collectionArr firstObject];
            YZLDiscuss *d1 = [self.collectionArr lastObject];
            [self.collectionArr insertObject:d1 atIndex:0];
            [self.collectionArr addObject:d0];
            self.header.arr = self.collectionArr;
        }

        NSArray *listArr = discuss.postList;
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.arr removeAllObjects];
        }
        
        for (NSDictionary *dic  in listArr) {
            YZLDiscuss *model = [YZLDiscuss DiscussWithDictionary:dic];
            [self.arr addObject:model];
        }
        
        [self.table footerEndRefreshing];
        [self.table headerEndRefreshing];
        [self.table reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.table footerEndRefreshing];
        [self.table headerEndRefreshing];
        UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"亲! 无网络! 请查看网络设置" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alertView1 show];
        DiscussViewController *sec = [DiscussViewController shareDiscussViewController];
//        [sec.navigationController presentViewController:alert animated:YES completion:nil];
    }];
    
    
}






- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"汽车论坛";
    // Do any additional setup after loading the view.
    [self creatTable];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(320*WIDTH/375, 580*HEIGHT/667, 30*WIDTH/375, 30*HEIGHT/667);
    [self.view addSubview:button];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"11"] forState:UIControlStateNormal];
    
    //bar颜色
    [self navigationbarColor];
}

- (void)button:(UIButton *)button {
    self.table.contentOffset = CGPointMake(0, -60);
}

+ (instancetype)shareDiscussViewController {
    static DiscussViewController *discuss = nil;
    static dispatch_once_t OnceToken;
    dispatch_once(&OnceToken, ^{
        discuss = [[DiscussViewController alloc] init];
    });
    return discuss;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
